#!/usr/bin/python3
# -*- coding:utf-8 -*-
""""
@Author: shijianbo
@Email:
@Time: 2023/6/11 15:17
@File: Aml__init__.py.py
"""
from time import sleep
from Common.Linux.ssh import SshUtil
from Common.Logs import logger
from Common.env import Env

class DatabaseService(object):

    def __init__(self,env=None):
        self.env=Env(env=env)
        self.dbType=self.env.dbType
        self.dbIp=self.env.dbConfig['ip']
        self.ssh=SshUtil(self.dbIp)

    def start(self):
        if self.dbType=='dameng':
            logger.info(self.ssh.exec('systemctl start DmServiceDMSERVER.service'))
        elif self.dbType == 'oracle':
            logger.info(self.ssh.execute('su - oracle'))
            logger.info(self.ssh.execute('sqlplus / as sysdba', 'SQL> '))
            logger.info(self.ssh.execute('startup', 'SQL> '))
        elif self.dbType=='mysql':
            logger.info(self.ssh.exec('source ~/.bash_profile && sh /opt/mysql/scripts/start.sh'))
        elif self.dbType=='oceanbase' and self.env.env=='oboracle':
            logger.info(self.ssh.exec('sh ~/obpkg_arm/obautoinstall.sh -r start'))
        else:
            raise RuntimeError(f'暂时不支持{self.dbType}')

    def stop(self):
        if self.dbType == 'dameng':
            logger.info(self.ssh.exec('systemctl stop DmServiceDMSERVER.service'))
        elif self.dbType=='oracle':
            logger.info(self.ssh.execute('su - oracle'))
            logger.info(self.ssh.execute('sqlplus / as sysdba','SQL> '))
            logger.info(self.ssh.execute('shutdown immediate', 'SQL> '))
        elif self.dbType=='mysql':
            logger.info(self.ssh.exec('source ~/.bash_profile && sh /opt/mysql/scripts/stop.sh'))
        elif self.dbType=='oceanbase' and self.env.env=='oboracle':
            logger.info(self.ssh.exec('sh ~/obpkg_arm/obautoinstall.sh -r stop'))
        else:
            raise RuntimeError(f'暂时不支持{self.dbType}')

    def restart(self):
        if self.dbType == 'dameng':
            logger.info(self.ssh.exec('systemctl restart DmServiceDMSERVER.service'))
        elif self.dbType == 'oracle':
            logger.info(self.ssh.execute('su - oracle'))
            logger.info(self.ssh.execute('sqlplus / as sysdba', 'SQL> '))
            logger.info(self.ssh.execute('shutdown immediate', 'SQL> '))
            logger.info(self.ssh.execute('startup', 'SQL> '))
        elif self.dbType=='mysql':
            logger.info(self.ssh.exec('source ~/.bash_profile && sh /opt/mysql/scripts/stop.sh'))
            sleep(3)
            logger.info(self.ssh.exec('source ~/.bash_profile && sh /opt/mysql/scripts/start.sh'))
        else:
            raise RuntimeError(f'暂时不支持{self.dbType}')

if __name__ == '__main__':
    # 实例化参数:oracle/mysql/dm/smoke-->即各个环境
    # 启动
    # DatabaseService('oboracle').start()
    # 停止
    # DatabaseService('oboracle').stop()
    # 重启
    DatabaseService('dm').restart()

